package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author kabuda
 * @create 2022-08-25 14:34
 */
@RequestMapping("/user")
@RestController
public class UserController {
    @RequestMapping("/getUserName")
    public Result getUserName(){
        try{
            //使用security框架认证后，框架会保存信息到上下文中，框架封装了方法为我们获取
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }


    }
}
